from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
from django.core.files.storage import FileSystemStorage

#  收集文件的信息表
class Collection(models.Model):
    projectname = models.CharField(max_length=50,primary_key=True)  #项目名
    username = models.CharField(max_length=10)  #收件人
    date = models.DateTimeField()           #截止时间
    otherinfo = models.TextField(default="")#备注信息
    # 文件格式控制
    word1 = models.CharField(max_length=20)     #字段1
    word2 = models.CharField(max_length=20)
    word3 = models.CharField(max_length=20)
    word4 = models.CharField(max_length=20)

    ppid = models.CharField(max_length=20)      #随机码
    user = models.ForeignKey(User,on_delete=models.DO_NOTHING)   #用户名

    def __str__(self):
        return self.projectname



# 覆盖保存文件
class mystorage(FileSystemStorage):
    def get_available_name(self, name,max_length=255):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name


# 文件收集列表
class FileList(models.Model):

    #自定义文件路径
    def upload_to(instance, filename):
        return '/'.join([settings.MEDIA_ROOT, instance.ppid, filename])

    projectname = models.ForeignKey(Collection,on_delete=models.DO_NOTHING)
    uploadtime = models.DateTimeField(auto_now=True)            #上传时间
    filename = models.CharField(max_length=255)               #文件名
    username = models.CharField(max_length=10,)               #用户名
    word1 = models.CharField(max_length=20)                  # 字段1
    word2 = models.CharField(max_length=20)
    filesize = models.FloatField()                             #文件大小
    ppid = models.CharField(max_length=20)  # 随机码
    file = models.FileField(upload_to=upload_to,storage=mystorage())    #文件保存路径


    def __str__(self):
        return self.username

    # 构造联合主键
    class Meta:
        unique_together = ("username","ppid")


